package org.ghost.consul.common.handler;

import org.ghost.consul.common.response.HttpRspDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by yarnliu on 2017-10-25.
 */
@ControllerAdvice
public class MyExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public HttpRspDTO privateExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder("参数错误:");
        int index = 0;
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(index).append(": ").append(fieldError.getDefaultMessage()).append(";");
            index++;
        }
        return new HttpRspDTO(false, "E400000", errorMessage.substring(0, errorMessage.length() - 1));
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public HttpRspDTO privateExceptionHandler(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder("参数错误:");
        int index = 0;
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append(";");
            index++;
        }
        return new HttpRspDTO(false, "E400000", errorMessage.substring(0, errorMessage.length() - 1));
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public HttpRspDTO privateExceptionHandler(HttpMessageNotReadableException ex) {
        return new HttpRspDTO(false, "E400000", "参数格式错误:" + ex.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public HttpRspDTO privateExceptionHandler(Throwable ex) {
        if (logger.isErrorEnabled()) {
            logger.error("系统错误: {}, {}", ex.getMessage(), ex);
        }
        return new HttpRspDTO(false, "E400000", "未捕获的异常:" + ex.getMessage());
    }
}
